﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SqlServer.Dts.Runtime;
using Bewise.SmartIndexManager.Core.Classes.IndexManager;
using Bewise.SmartIndexManager.Core;

namespace Bewise.SmartIndexManager
{
    [DtsTask
    (
        // Nom affiché sur la ToolBox
    DisplayName = "SmartIndexManager",
    Description = "SmartIndexManager",
    RequiredProductLevel = DTSProductLevel.None,
    TaskContact = "SmartIndexManager",
    UITypeName = "Bewise.SmartIndexManager.UI.SmartIndexManager_UI, BewiseSmartIndexManager, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=44bbb7dd8ea419c4"
    )]
    public class SmartIndexManager : Task
    {
        public string SqlServerConnection { get; set; }
        public string TaskInfos { get; set; }
        private IDTSLogging _logSSIS;
        private bool _logIsEnabled;

        public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction)
        {
            _logSSIS = log;

            // initialisation du delegué pour le log
            IndexManager.LogSSIS_OnInformation = (msg, start, finish) => LogSSIS_OnInformation(msg, start, finish);

            DTSExecResult resultat;
            try
            {
                // deserialisation de TaskInfos
                var taskInfos = Tools.Deserialize(this.TaskInfos);

                // récupération du booléen de Log Enabled
                _logIsEnabled = taskInfos.LogOnInformationIsEnabled;

                // lancement de traitement avec en parametre l'objet taskInfos
                IndexManager.Execute(taskInfos);

                resultat = DTSExecResult.Success;
            }
            catch (Exception ex)
            {
                // écriture dans le Log de SSIS de l'erreur
                LogSSIS_OnError(ex.Message, DateTime.Now, DateTime.Now);
                throw ex;
            }
            return resultat;
        }

private void LogSSIS_OnInformation(string msg, DateTime start, DateTime finish)
{
    LogSSIS("OnInformation", msg, start, finish);
}

private void LogSSIS_OnError(string msg, DateTime start, DateTime finish)
{
    LogSSIS("OnError", msg, start, finish);
}

private void LogSSIS(string eventName, string msg, DateTime start, DateTime finish)
{
    // Test si le log complet est demandé
    if (_logIsEnabled)
    {
        Byte[] data = null;
        // écriture dans le Log SSIS
        _logSSIS.Log(eventName, Environment.MachineName, Environment.UserName, "SmartIndexManager", null, null,
                     msg, start, finish, 1, ref data);
    }
}
    }
}
